<?php
namespace plugin\entity_manager\src\query;

/**
 * The MIT License
 *
 * Copyright (c) <year> <copyright holders>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author Damiano Ciarla
 * @package plugin
 * @subpackage entity_manager/class/function
 */
class Insert extends AbstractQuery implements InterfaceQuery
{
	/**
	 * Lista dei valori da bindare
	 *
	 * @var array
	 */
	public $_bindSetValue = array();

	public function __construct(\plugin\entity_manager\src\AbstractEntity $entity)
	{
		$this->_entity = &$entity;
	}

	/**
	 * Metodo che esegue la query costruita in base ai valori impostati nella entity
	 * o a quelli aggiuntivi settati con i metodi presenti in questa classe
	 *
	 * @param boolean $ignore Imposta se eseguire una INSERT INGORE o una insert classica
	 *
	 * @return int Ultimo id inserito. Se esiste un campo "auto_increment" nella tabella il suo
	 * valore viene riempito con l'id trovato quindi da poterlo ritrovare all'interno della
	 * entity su cui è stata eseguita l'operazione di inserimento
	 */
	public function execute($ignore = false, $connectionName = null)
	{
		$properties = $this->_entity->getProperty();

		$db = \plugin\entity_manager\src\EntityManager::getConfig($connectionName)->getConnection();

		$prepare = $db->prepare($this->_getSqlQuery($ignore));

		foreach($this->_bindSetValue as $param)
			$prepare = $prepare->bindParam("?", $param['value'], $param['type']);

		$result = $prepare->execute();

		$lastInsertId = null;

		if(isset($properties['ENTITY']['AUTO_INCREMENT']) && $properties['ENTITY']['AUTO_INCREMENT'] !== null)
		{
			$fieldAI = $properties['ENTITY']['AUTO_INCREMENT'];
			$lastInsertId = $db->lastInsertId();

			$this->_entity->$fieldAI = $lastInsertId;
		}

		return $lastInsertId;
	}

	/**
	 * Metodo che si occupa di costruire la query in base ai valori impostati nella entity o ai
	 * parametri aggiuntivi settati dall'utilizzo degli altri metodi presenti in questa classe
	 *
	 * @return string
	 */
	private function _getSqlQuery($ignore = false)
	{
		$properties = $this->_entity->getProperty();

		$sql = "";

		foreach($properties['FIELDS'] as $field => $property)
		{
			if($property['value'] !== null)
			{
				$sql .= (($sql == "") ? "" : ", ") . $properties['ENTITY']['TABLE'] . "." . $field . " = ?";

				$this->_bindSetValue[] = array("type" => $this->_getBindType($property['properties']['TYPE']), "value" => $property['value']);
			}
		}

		$sql = (($ignore) ? "INSERT IGNORE" : "INSERT") . " INTO " . $properties['ENTITY']['TABLE'] . " SET " . $sql;

		return $sql;
	}
}
?>
